package com.ztesoft.zsmart.zcm.monitor.config;

import com.google.common.collect.Range;
import com.ztesoft.zsmart.core.utils.DateUtil;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class NmsRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
        RangeShardingValue<Date> rangeShardingValue) {
        final ArrayList<String> result = new ArrayList<>();
        Range<Date> range = rangeShardingValue.getValueRange();
        Date start = range.lowerEndpoint();
        Date end = range.upperEndpoint();
        List<String> dateStrBetween = getDateStrBetween(start, end);
        for (String date : dateStrBetween) {
            for (String availableTargetName : availableTargetNames) {
                if (availableTargetName.endsWith(date)) {
                    result.add(availableTargetName);
                    break;
                }
            }
        }
        return result;
    }

    private List<String> getDateStrBetween(Date startTime, Date endTime) {
        List<String> result = new ArrayList<>();
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.setTime(startTime);
        end.setTime(endTime);
        Calendar curr = start;
        while (curr.before(end)) {
            result.add(DateUtil.date2String(curr.getTime(), "yyyyMM"));
            curr.add(Calendar.MONTH, 1);
        }
        result.add((DateUtil.date2String(end.getTime(), "yyyyMM")));
        return result.stream().distinct().collect(Collectors.toList());
    }

}
